package top.codecrab.eblog.utils;


import freemarker.template.Configuration;
import freemarker.template.Template;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.mail.MailProperties;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;

import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.time.LocalDate;
import java.time.LocalTime;
import java.util.HashMap;
import java.util.Map;

/**
 * 发邮件工具类
 */
@Slf4j
@Component
@RequiredArgsConstructor
public final class EmailUtils {

    private final MailProperties mailProperties;

    private final JavaMailSender mailSender;

    /**
     * @param params       发送邮件的主题对象 object
     * @param title        邮件标题
     * @param templateName 模板名称
     */
    public boolean sendMessageMail(String to, Object params, String title, String templateName) {
        try {
            MimeMessage mimeMessage = mailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
            //发送者
            helper.setFrom(mailProperties.getUsername());
            //接收者
            helper.setTo(InternetAddress.parse(to));
            //邮件标题
            helper.setSubject("【" + title + "-" + LocalDate.now() + " " + LocalTime.now().withNano(0) + "】");

            Map<String, Object> model = new HashMap<>();
            model.put("params", params);
            Configuration configuration = new Configuration(Configuration.VERSION_2_3_28);
            configuration.setClassForTemplateLoading(this.getClass(), "/templates");

            Template template = configuration.getTemplate(templateName);
            String text = FreeMarkerTemplateUtils.processTemplateIntoString(template, model);

            helper.setText(text, true);
            mailSender.send(mimeMessage);
            log.info("发送邮件成功！");
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }
}
